const incomeDAO = require('../DAO/incomeDAO.js');
const { getOpenid } = require('../dbCloud.js');
const utils = require('../lib/utils.js');


var INCOME_TYPE_MAP = {
  0: '工资',
  1: '兼职',
  2: '理财',
  3: '礼金',
  4: '红包',
  99: '其他'
};

/**
 * 求和总支出
 */
const queryTotalIncomes = async (params) => {
  var total = 0;
  var currentMonthTotal = 0;
  var allAccounts = await incomeDAO.queryAllIncomes(getOpenid());
  allAccounts.data.forEach(item => {
    var incomeValue = item.incomeValue / 1 || 0;
    total += incomeValue;
    if (utils.isCurrentMonth(item.incomeTime)) {
      currentMonthTotal += incomeValue;
    }
  });
  return {
    currentMonthTotal: currentMonthTotal.toFixed(2),
    total: total.toFixed(2)
  };
};

/**
 * 根据主键获取收入
 */
const queryIncomeById = async (params) => {
  var id = params.id;
  var result = await incomeDAO.queryIncomeById(id);
  result.data.incomeTypeName = INCOME_TYPE_MAP[result.data.incomeType];
  return result;
};

/**
 * 根据主键产出收入
 */
const deleteIncomeById = async (id) => {
  var id = params.id;
  return incomeDAO.deleteIncomeById(id);
};

/**
 * 获取收入列表
 */
const queryIncomes = async (params) => {
  // 用户
  var userId = getOpenid();
  var result = await incomeDAO.queryIncomes(userId);
  result.data.forEach(item => {
    item.incomeTypeName = INCOME_TYPE_MAP[item.incomeType];
  });
  var { total, currentMonthTotal } = await queryTotalIncomes();
  return {
    list: result.data,
    total: total,
    currentMonthTotal: currentMonthTotal
  };
};

const addIncome = async (params) => {
  params._openid = getOpenid();
  return await incomeDAO.addIncome(params);
};

module.exports = {
  queryIncomes,
  queryIncomeById,
  deleteIncomeById,
  addIncome
};